package com.suneast.suneaststore.modules.personal.wallet;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;

import com.suneast.suneaststore.R;
import com.suneast.suneaststore.app.AccountManager;
import com.suneast.suneaststore.bean.personal.bank.BankCardBean;
import com.suneast.suneaststore.modules.common.Flag;
import com.suneast.suneaststore.modules.personal.PersonalFragment;
import com.suneast.suneaststore.modules.personal.order.event.WithdrawResult;
import com.suneast.suneaststore.modules.personal.wallet.bankcard.BankCardListFragment;
import com.suneast.suneaststore.modules.personal.wallet.bankcard.event.GotBankCardList;
import com.suneast.suneaststore.modules.personal.wallet.event.BalanceValueChange;
import com.suneast.suneaststore.ui.customview.MoneyTextWatcher;
import com.suneast.suneaststore.ui.fragments.BaseFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class WithdrawFragment extends BaseFragment {
    public static final int RequestCode = 0;

    @Override
    public int setLayout() {
        return R.layout.fragment_withdraw;
    }

    private double balanceValue = 0.00;
    private double goodsValue = 0.00;

    public WithdrawFragment withBalanceValue(double value) {
        balanceValue = value;
        return this;
    }

    public WithdrawFragment withGoodsValue(double value) {
        goodsValue = value;
        return this;
    }

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_total_value)
    TextView totalValueTv;
    @BindView(R.id.tv_bank_name)
    TextView bankNameTv;
    @BindView(R.id.tv_go_to_select_card)
    TextView goSelectCardTv;
    @BindView(R.id.tv_balance_value)
    TextView balanceValueTv;
    @BindView(R.id.tv_goods_value_tip)
    TextView goodsValueTip;
    @BindView(R.id.line_goods_withdraw)
    View goodsWithdrawLine;
    @BindView(R.id.tv_goods_value)
    TextView goodsValueTv;
    @BindView(R.id.tv_bank_card_number)
    TextView cardNumberTv;
    @BindView(R.id.cb_balance_withdraw)
    CheckBox balanceWithdrawCb;
    @BindView(R.id.cb_goods_balance_withdraw)
    CheckBox goodsBalanceWithdrawCb;

    @BindView(R.id.et_withdraw_value)
    AppCompatEditText withdrawEt;

    @OnClick({R.id.layout_bank_card_info, R.id.btn_withdraw})
    public void onViewClick(View view) {
        if (view.getId() == R.id.layout_bank_card_info) {
            //去选择银行卡
            startForResult(new BankCardListFragment().withType(BankCardListFragment.TypeChoose),
                    RequestCode);
        } else if (view.getId() == R.id.btn_withdraw) {
            // 发起提现
            if (withDrawType != -1) {
                if (bankId != -1) {
                    String withDrawValueStr = withdrawEt.getText().toString();
                    if (withDrawValueStr.length() > 0) {
                        double moneyValue = Double.valueOf(withDrawValueStr);
                        if (moneyValue > 0) {
                            if (withDrawType == 1) {
                                if (moneyValue > balanceValue) {
                                    Toast.makeText(_mActivity, "您输入的额度已超出你的余额额度哦", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                            } else if (withDrawType == 2) {
                                if (moneyValue > balanceValue) {
                                    Toast.makeText(_mActivity, "您输入的额度已超出你货款的额度哦", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                            }
                            if (moneyValue < 100) {
                                Toast.makeText(_mActivity, "提现额度至少为100", Toast.LENGTH_SHORT).show();
                                return;
                            }
                            WalletHandler.requestWithdraw(withDrawType, moneyValue, bankId);
                        } else {
                            Toast.makeText(_mActivity, "提现金额需大于0", Toast.LENGTH_SHORT).show();
                        }
                    }
                } else {
                    Toast.makeText(_mActivity, "请选择一张银行卡", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(_mActivity, "请选择您要提现的类别", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        EventBus.getDefault().register(this);
        initView();
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        if (requestCode == RequestCode && resultCode == BankCardListFragment.SucessCode) {
            bankId = data.getInt("card_id");
            bankNameTv.setText(data.getString("bank_name"));
            cardNumberTv.setText(data.getString("card_num"));
        }
    }

    private int withDrawType = 1; // 0 :余额提现  1:货款提现
    private int bankId = -1;
    DecimalFormat df;

    private void initView() {
        toolbar.setNavigationOnClickListener(v -> pop());
        if (AccountManager.getLevel() == 1) {
            goodsValueTip.setVisibility(View.GONE);
            goodsValueTv.setVisibility(View.GONE);
            goodsWithdrawLine.setVisibility(View.GONE);
        }
        balanceWithdrawCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    if (goodsBalanceWithdrawCb.isChecked()) {
                        goodsBalanceWithdrawCb.setChecked(false);
                    }
                    withDrawType = 1;
                } else {
                    withDrawType = -1;
                }
            }
        });

        goodsBalanceWithdrawCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    if (balanceWithdrawCb.isChecked()) {
                        balanceWithdrawCb.setChecked(false);
                    }
                    withDrawType = 2;
                } else {
                    withDrawType = -1;
                }
            }
        });
        df = new DecimalFormat("0.00");
        totalValueTv.setText(df.format(balanceValue + goodsValue));
        balanceValueTv.setText(df.format(balanceValue));
        goodsValueTv.setText(df.format(goodsValue));
        withdrawEt.addTextChangedListener(new MoneyTextWatcher(withdrawEt));
        WalletHandler.requestBackCardList();
    }

    List<BankCardBean> bankCardList;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGotBankCardList(GotBankCardList event) {
        Log.e(TAG, "onGotBankCardList: size = " + event.getBankCardList().size());
        bankCardList = event.getBankCardList();
        if (event.getBankCardList() != null && event.getBankCardList().size() > 0) {
            BankCardBean bean = event.getBankCardList().get(0);
            bankId = bean.getId();
            bankNameTv.setText(bean.getBankName());
            cardNumberTv.setText(bean.getNum());
            goSelectCardTv.setText("更换银行卡");
        } else {
            goSelectCardTv.setText("去添加银行卡");
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGotWithdrawResult(WithdrawResult result) {
        if (result.getResult() == Flag.Result.SUCCEED) {
            PersonalFragment.balanceValue = result.getBalanceValue();
            EventBus.getDefault().post(new BalanceValueChange());
            totalValueTv.setText(new DecimalFormat("0.00").format(result.getBalanceValue()));
            Toast.makeText(_mActivity, "提现成功,提现金额将会在1-3天内到账", Toast.LENGTH_SHORT).show();
            withdrawEt.setText("");
        } else {
            Toast.makeText(_mActivity, "提现失败:" + result.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }
}
